package wyw.sell.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import wyw.sell.entity.Final_Warehouse;
import wyw.sell.entity.Result;
import wyw.sell.mapper.SellMapper;

import java.util.*;

@Service
public class SellServiceImpl extends ServiceImpl<SellMapper, Result> implements SellService {
    @Autowired
    private SellMapper sellMapper;

    @Autowired
    private SellService sellService;

    @Override
    public List<Final_Warehouse> Final2101ToRes() {
        //查到21年1月的期初数量，作为20年12月的期末数量
        List<Final_Warehouse> final_warehouses = sellMapper.Final2101ToRes();
        //将数据封装到result
        List<Result> base = new ArrayList<>(final_warehouses.size());
        for (Final_Warehouse final_warehouse : final_warehouses) {
            Result result = new Result();
            result.setMaterialCode(final_warehouse.getMaterialCode());
            result.setMaterialName(final_warehouse.getMaterialName());
            result.setNextmonthCalculate(final_warehouse.getSumBeginNumber());
            result.setYear("2020");
            result.setMonth("12");
            result.setNextYear("2021");
            result.setNextMonth("1");
            base.add(result);
        }
        sellMapper.insertResultBase(base);
        return final_warehouses;
    }

    @Override
    public void calculate() {
        //先处理20年12月的，再迭代
        String[] years = new String[2];
        years[0] = "2019";
        years[1] = "2020";
        String[] months = new String[12];
        for (int i = 1; i <= 12; i++) {
            months[i - 1] = String.valueOf(i);
        }
        for (String year : years) {
            for (String month : months) {
                List<Result> inputList = sellMapper.selectInput(year, month);
                List<Result> outputList = sellMapper.selectOutput(year, month);
                insertOrUpdateResult(inputList, year, month);
                insertOrUpdateResult(outputList, year, month);
            }
        }
        //将21年1月的放进result
        List<Final_Warehouse> final_warehouses = sellMapper.Final2101ToRes();
        for (Final_Warehouse final_warehouse : final_warehouses) {
            Result result = new Result();
            result.setYear("2020");
            result.setMonth("12");
            result.setMaterialCode(final_warehouse.getMaterialCode());
            result.setMaterialName(final_warehouse.getMaterialName());
            result.setNextmonthCalculate(final_warehouse.getSumBeginNumber());
            QueryWrapper<Result> wrapper = new QueryWrapper<>();
            wrapper.eq("material_code", result.getMaterialCode()).eq("year", "2020").eq("month", "12");
            if (sellMapper.selectOne(wrapper) == null) {
                sellMapper.insert(result);
            }
            else {
                sellMapper.update(result, wrapper);
            }
        }
        //倒推迭代计算
        List<String> yearsList = Arrays.asList(years);
        List<String> monthsList = Arrays.asList(months);
        Collections.reverse(yearsList);
        Collections.reverse(monthsList);
        for (String year : yearsList) {
            for (String month : monthsList) {
                QueryWrapper<Result> wrapper = new QueryWrapper<>();
                wrapper.eq("year", year).eq("month", month);
                //防止中文乱码，将中文字段设为""
                List<Result> allResult = sellMapper.selectList(null);
                for (Result result : allResult) {
                    result.setMaterialName("");
                    sellMapper.update(result, new QueryWrapper<Result>()
                            .eq("material_code", result.getMaterialCode())
                            .eq("year", result.getYear())
                            .eq( "month", result.getMonth()));
                }
                List<Result> results = sellMapper.selectList(wrapper);
                //计算此年月，并赋值给上年月的nextmonthCalculate
                calculateList(results);
            }
        }
    }

    public void insertOrUpdateResult(List<Result> list, String year, String month) {
        for (Result item : list) {
            QueryWrapper<Result> wrapper = new QueryWrapper<>();
            wrapper.eq("material_code", item.getMaterialCode()).eq("year", year).eq("month", month);
            Result selectOne = sellMapper.selectOne(wrapper);
            //不为空说明有记录，更新
            if (selectOne != null) {
                selectOne.setMonthInput(item.getMonthInput());
                sellMapper.update(item, wrapper);
            }
            else {
                item.setMonth(month);
                item.setYear(year);
                sellMapper.insert(item);
            }

        }
    }

    public void calculateList(List<Result> list) {
        for (Result result : list) {
            double calculate = result.getNextmonthCalculate() + result.getMonthOutput() - result.getMonthInput();
            result.setCalculate(calculate);
            QueryWrapper<Result> wrapper = new QueryWrapper<>();
            wrapper.eq("material_code", result.getMaterialCode()).eq("year", result.getYear()).eq("month", result.getMonth());
            sellMapper.update(result, wrapper);
            //将该编码此月的calculate作为上月的nextmonthCalculate
            QueryWrapper<Result> wrapper2 = new QueryWrapper<>();
            int lastMonth = 0;
            String year = "2020";
            if ("1".equals(result.getMonth())) {
                lastMonth = 12;
                year = "2019";
            }
            else {
                lastMonth = Integer.parseInt(result.getMonth()) - 1;
                year = result.getYear();
            }
            wrapper2.eq("material_code", result.getMaterialCode()).eq("year", year).eq("month", String.valueOf(lastMonth));
            Result lastResult = sellMapper.selectOne(wrapper2);
            if (result.getMonth().equals("8") && result.getMaterialCode().equals("S2600DA") && result.getYear().equals("2019")) {
                System.out.println("====");
                System.out.println("========");
            }
            if (lastResult != null) {
                lastResult.setNextmonthCalculate(calculate);
                sellMapper.update(lastResult, wrapper2);
            }
        }
    }
}
